# 交易记录模型
from datetime import datetime

# 从app中导入共享的db实例
from app import db

class Transaction(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    stock_id = db.Column(db.Integer, db.ForeignKey('stock.id'), nullable=False)
    portfolio_id = db.Column(db.Integer, db.ForeignKey('portfolio.id'), nullable=False)
    transaction_type = db.Column(db.String(10), nullable=False)  # 'buy' 或 'sell'
    quantity = db.Column(db.Integer, nullable=False)
    price = db.Column(db.Float, nullable=False)
    total_amount = db.Column(db.Float, nullable=False)
    transaction_date = db.Column(db.DateTime, default=datetime.utcnow)
    status = db.Column(db.String(20), default='completed')  # 'pending', 'completed', 'failed'
    
    @property
    def profit_loss(self):
        """计算交易盈亏（仅对卖出交易有效）"""
        if self.transaction_type == 'sell':
            # 获取买入成本
            buy_transactions = Transaction.query.filter_by(
                user_id=self.user_id,
                stock_id=self.stock_id,
                transaction_type='buy'
            ).order_by(Transaction.transaction_date).all()
            
            remaining_quantity = self.quantity
            total_cost = 0
            
            for buy in buy_transactions:
                if remaining_quantity <= 0:
                    break
                
                if buy.quantity <= remaining_quantity:
                    total_cost += buy.quantity * buy.price
                    remaining_quantity -= buy.quantity
                else:
                    total_cost += remaining_quantity * buy.price
                    remaining_quantity = 0
            
            if remaining_quantity == 0:
                return self.total_amount - total_cost
            else:
                return None  # 无法计算，因为没有足够的买入记录
        else:
            return None  # 买入交易不计算盈亏
        
    def __repr__(self):
        return f'<Transaction {self.transaction_type} {self.quantity} shares of {self.stock_id} at {self.price}>'